/**
 * @file frameRater.h
 * @author SDK_TEAM
 * @brief
 * @version 0.1
 * @date 2022-11-09
 *
 * Copyright:
 * © 2018 北京灵汐科技有限公司 版权所有。
 * 注意：以下内容均为北京灵汐科技有限公司原创，未经本公司允许，不得转载，否则将视为侵权；对于不遵守此声明或者其他违法使用以下内容者，本公司依法保留追究权。
 * © 2018 Lynxi Technologies Co., Ltd. All rights reserved.
 * NOTICE: All information contained here is, and remains the property of Lynxi.
 * This file can not be copied or distributed without the permission of Lynxi
 * Technologies Co., Ltd.
 *
 */

#pragma once

#include <sys/time.h>
#include <iostream>
#include <string>
#include "logging.h"

// 帧率统计类
class FrameRater {
 protected:
  struct timeval m_tBegin;    // 开始时间
  long m_interval = 1000000;  // 打印间隔
  long m_iFrames = 1;         // 总帧数
  std::string m_strTitle;     // 打印标题

 public:
  FrameRater() { gettimeofday(&m_tBegin, 0); }

  FrameRater(const std::string &str) : m_strTitle(str) {
    gettimeofday(&m_tBegin, 0);
  }

  // 设置标题
  void SetTitle(const std::string &strTitle) { m_strTitle = strTitle; }

  // 设置打印间隔
  bool SetInterval(long iInterval) {
    if (iInterval > 0) {
      m_interval = iInterval * 1000000;
      return true;
    }

    return false;
  }

  // 添加帧
  void AddFrame(int iFrame = 1) {
    m_iFrames += iFrame;
    struct timeval tCur;
    gettimeofday(&tCur, 0);
    long secTime = tCur.tv_sec - m_tBegin.tv_sec;
    long usecTime = tCur.tv_usec - m_tBegin.tv_usec + secTime * 1000000;
    if (usecTime > m_interval) {
      int rate = m_iFrames * 1000000 / usecTime;
      printf("%s frame rate is: %d\n", m_strTitle.c_str(), rate);
      m_iFrames = 0;
      m_tBegin = tCur;
    }
  }
};
